<!--
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 -->
<template>
	<view class="activityDetails-box flex">
		<view class="activityDetails-info w100">
			<view class="activityDetails-head">
				<swiper class="swiper" circular :indicator-dots="true" :autoplay="true">
					<swiper-item class="swiper-img-item" v-for="(item,index) in matchInfo.imageList" :key="index">
						<image :src="item" @click="previewImage(matchInfo.imageList,index)" class="img-item"
							mode="aspectFill">
						</image>
					</swiper-item>
				</swiper>
			</view>
			<!-- <view class="content-code" @click="getSignCode">
				<view class="text-box flex-center">
					<text class="text">签到码</text>
				</view>
				<image src="../static/code-icon.png" class="code" mode=""></image>
			</view> -->
		</view>

		<!-- 主体 -->
		<view class="main w100">
			<!-- tabList -->
			<up-sticky offset-top="0">
				<view class="tab-box w100">
					<up-tabs :activeStyle="{
					'fontWeight': 'bold',
					'fontSize': '30rpx',
					'color': '#fff'
				}" lineColor="linear-gradient( 270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%)" :inactiveStyle="{
				 	'fontWeight': 500,
				 	'fontSize': '30rpx',
				 	'color': '#9A9B9C'
				 }" :list="tabList" :current="tabIndex" @change="changeTab"></up-tabs>
				</view>
			</up-sticky>
			<view class="main-content w100">
				<swiper class="swiper-content" @change="changeSwiper" :current="tabIndex">
					<!-- 阶段 -->
					<swiper-item class="swiper-content-item">
						<!-- <scroll-view scroll-y style="height: 100%;width: 100%;"> -->
						<stageItemVue @refreshData="refreshData" @getlocationBysign="getlocationBysign"
							@checkedSign="checkedSign"></stageItemVue>
						<!-- </scroll-view> -->
					</swiper-item>
					<!-- 详情 -->
					<swiper-item class="swiper-content-item">
						<scroll-view scroll-y style="height: 100%;width: 100%;">
							<detailsContentVue @getlocationBysign="getlocationBysign" @refreshData="refreshData">
							</detailsContentVue>
						</scroll-view>
					</swiper-item>
					<!-- 人员 -->
					<swiper-item class="swiper-content-item">
						<scroll-view scroll-y style="height: 100%;width: 100%;" @scrolltolower="getMoreJoiner">
							<view class="personnel-box w100" v-if="joinerInfo.list.length>0">
								<view class="personnel-item flex-row-center" v-for="(item,index) in joinerInfo.list"
									:key="index">
									<view class="personnel-left flex-row-center">
										<view class="ava">
											<up-avatar :default-url="errImg" :src="item.avatar" mode="aspectFill"
												size="68rpx"></up-avatar>
										</view>
										<!-- <image :src="item.avatar" class="ava" mode="aspectFill"></image> -->
										<text class="name">{{item.real_name}}</text>
									</view>
									<view class="personnel-right flex-row-center">
										<text class="point">{{item.newMobile}}</text>
									</view>
								</view>
								<view class="view-more">
									<up-loadmore :status="joinerInfo.status" />
								</view>
							</view>
							<view class="not-list-view" v-else>
								<text class="text">该赛事还没有人员参加~</text>
							</view>
						</scroll-view>
					</swiper-item>
				</swiper>
			</view>
		</view>
	</view>
	<!-- 报名 -->
	<up-popup :show="signShow" round="18rpx" @close="closeSign" :closeOnClickOverlay="false" :closeable="true">
		<signPopupVue :matchId="matchId" :signShow="signShow" @checkedSign="checkedSign"></signPopupVue>
	</up-popup>
	<up-popup :show="signCodePop" closeable :safeAreaInsetBottom="false" round="18rpx" bgColor="#191c1F" mode="center"
		@close="closesignCode">
		<view class="signCode-box flex-row-center">
			<text class="title">签到二维码</text>
			<view class="code-box w100 flex-center">
				<up-qrcode ref="upCode" :size="220" :val="signCode"></up-qrcode>
			</view>
			<view class="option-box flex-row-center w100">
				<view class="option-btn flex-center" @click="saveCode">
					<text class="text">保存</text>
				</view>
			</view>
		</view>
	</up-popup>
	<up-popup :show="signMapShow" bgColor="transparent" mode="center" round="18rpx" :safeAreaInsetBottom="false">
		<view class="signShow-box">
			<view class="map-content flex-row-center w100">
				<view class="content-box w100 flex-center">
					<map class="map-box" v-if="positionInfo.show" :latitude="positionInfo.latitude"
						:circles="positionInfo.circles" :longitude="positionInfo.longitude"
						:markers="positionInfo.covers" :night-status="true" :scale="positionInfo.scale">
					</map>
					<up-loading-icon color="#66DEC2" v-else></up-loading-icon>
				</view>
				<view class="sign-content flex-center">
					<text class="detail">在举办赛事地点300m范围内即可签到</text>
					<view class="sign-btn-err flex-center" v-if="positionInfo.status==-1"
						@click="getlocationBysign('noopen')">
						<text class="text">定位</text>
						<text class="text">失败</text>
						<up-icon name="reload" color="#fff" size="28rpx"></up-icon>
					</view>
					<view class="sign-bnt" v-else @click="signRound">
						<text class="text">立即</text>
						<text class="text">签到</text>
					</view>
				</view>

			</view>

			<view class="close-btn flex-center" @click="closesignRound">
				<up-icon name="close" color="#dedede" size="48rpx"></up-icon>
			</view>
		</view>
	</up-popup>
</template>

<script setup>
	import signPopupVue from '../components/signPopup.vue';
	import stageItemVue from '../components/stageItem.vue';
	import detailsContentVue from '../components/detailsContent.vue';
	import personnelItemVue from '../components/personnelItem.vue';
	import {
		getLocationInf
	} from '@/utils/getLocation.js';
	import {
		userInfoStore
	} from '@/stores/user';
	import {
		handleDistance,
		formatDate,
		maskPhoneNumber,
		isMillisecondTimestamp
	} from '@/utils/utools.js';
	import {
		matchInfoStore
	} from '@/stores/match';
	import {
		configInfoStore
	} from '@/stores/config.js';
	const matchStore = matchInfoStore();
	const positionInfo = reactive({
		latitude: 30.5702,
		longitude: 104.06476,
		covers: [],
		circles: [],
		scale: 16,
		status: -1,
		show: false
	})
	const {
		configInfo
	} = configInfoStore();
	const signMapShow = ref(false);
	const upCode = ref(null);
	const signCodePop = ref(false);
	const signCode = ref('');
	const errImg = ref(computed(() => configInfo.user_default_avatar?.value))
	const userStore = userInfoStore();
	const addressInfo = computed(() => userStore.addressInfo);
	const tabIndex = ref(0);
	const signShow = ref(false);
	const status = ref('loading');
	const matchId = ref(0);
	const matchInfo = ref({
		imageList: [],
		name: '',
		isDiyFull: 0, //自定义是否满员
	});
	const joinerInfo = reactive({
		list: [],
		page: 1,
		status: 'loadmore'
	})
	const tabList = [{
			name: '阶段'
		},
		{
			name: '详情'
		},
		{
			name: '人员'
		}
	]
	onLoad(async (e) => {
		console.log('赛事参数', e);
		if (e.id) {
			matchId.value = e.id;
			if (addressInfo.value) {
				getMatchDetail(e.id);
			} else {
				uni.showLoading({
					title: '获取定位中'
				})
				const res = await getLocationInf()
				if (res.address) {
					setTimeout(() => {
						uni.hideLoading()
					}, 600);
					userStore.addressInfo = res;
					getMatchDetail(e.id);
				}
			}
			getMatchJoiner(e.id); //获取人员
		}
	});
	onUnload(() => {
		matchStore.setMatchInfo(null);
	});
	onPullDownRefresh(async () => {
		uni.showLoading({
			title: '刷新中'
		})
		tabIndex.value = 0;
		joinerInfo.list = [];
		joinerInfo.status = 'loadmore';
		joinerInfo.page = 1;
		await getMatchDetail(matchId.value);
		await getMatchJoiner(matchId.value);
		uni.stopPullDownRefresh();
	});
	const getMatchDetail = async (id) => {
		const res = await $Api.match.getMatchDetail({
			id,
			lat: addressInfo.value?.latitude,
			lng: addressInfo.value?.longitude
		}, true);
		if (res.code == 1) {
			positionInfo.covers.push({
				id: 1,
				latitude: res.data?.lat,
				longitude: res.data?.lng,
				width: 29,
				height: 36,
				iconPath: '../../static/nearby/positioning_icon.png'
			})
			positionInfo.circles.push({
				latitude: res.data?.lat,
				longitude: res.data?.lng,
				radius: 300,
				color: '#7EDE9E',
				fillColor: 'rgba(108, 199, 190, 0.38)'
			})
			positionInfo.show = true;


			let imageList = [];
			let sign_end_text = '';
			let sign_start_text = '';
			let match_text = '';
			let countDownstatus = 0;
			let isDiyFull = 0;
			let my_scoreWrite_auth = 0; //编辑分数权限
			let my_roundStart_auth = 0; //开启下一轮权限
			let my_matchEnd_auth = 0; //结束比赛权限
			let stepsIndex = 0; //比赛阶段标识，默认0
			let isLastRound = 0; //是否最后一轮
			if (res.data.image) {
				if (typeof res.data.image === 'string') {
					imageList = res.data.image.split(',');
				} else if (Array.isArray(res.data.image)) {
					res.data.image.forEach(item => {
						imageList.push(item.url);
					})
				}
			};
			if (res.data.juli) {
				res.data.juli = handleDistance(res.data.juli);
			}
			if (res.data.sign_end_date) {
				sign_end_text = formatDate(res.data.sign_end_date);
			}
			if (res.data.sign_start_date) {
				sign_start_text = formatDate(res.data.sign_start_date);
			}
			if (res.data.referee && res.data.referee.length > 0) {
				my_scoreWrite_auth = res.data.referee.includes('score_write') ? 1 : 0;
				my_roundStart_auth = res.data.referee.includes('round_start') ? 1 : 0;
				my_matchEnd_auth = res.data.referee.includes('match_end') ? 1 : 0;
			}
			if (res.data.match_date) {
				match_text = formatDate(res.data.match_date);
			}
			if (res.data.current_round != undefined && res.data.current_round != null) { //判断是否最后一轮
				if (Number(res.data.current_round) >= res.data.rounds) {
					isLastRound = 1;
				}
			}
			if (res.data.status == 0) { //赛事未结束判断状态
				countDownstatus = computeDate(res.data.sign_start_date, res.data.sign_end_date, res.data
					.match_date);
				stepsIndex = computeStep(res.data.match_date);
			} else if (res.data.status == 1) { //赛事已经结束
				countDownstatus = -1;
				stepsIndex = 2;
			}
			if (res.data.join_count && res.data.join_count >= res.data.people_count) { //判断是否满员
				isDiyFull = 1;
			}

			matchInfo.value = {
				...res.data,
				imageList,
				match_text,
				sign_start_text,
				sign_end_text,
				countDownstatus,
				isDiyFull,
				stepsIndex,
				my_scoreWrite_auth,
				my_roundStart_auth,
				my_matchEnd_auth,
				isLastRound
			}
			matchStore.setMatchInfo(matchInfo.value);
			console.log('matchInfo', matchInfo.value);
		} else {
			uni.$u.toast(res.msg)
		}
	}
	const computeDate = (startDate, endDate, matchDate) => {
		let status = 0
		if (!isMillisecondTimestamp(startDate)) { //判断毫秒级时间戳
			startDate = startDate * 1000
		}
		if (!isMillisecondTimestamp(endDate)) { //判断毫秒级时间戳
			endDate = endDate * 1000
		}
		if (!isMillisecondTimestamp(matchDate)) { //判断毫秒级时间戳
			matchDate = matchDate * 1000
		}
		let newDate = new Date().getTime();
		if (newDate > matchDate) { //赛事进行中
			status = 3;
		} else if (newDate > endDate && newDate <= matchDate) { //报名已经结束，比赛未开始
			status = 2;
		} else if (newDate > startDate && newDate <= endDate) { //报名进行中，距结束多少时间
			status = 1;
		} else if (newDate <= startDate) { //报名未开始 距开始多少时间
			status = 0;
		}
		return status;
	};
	const computeStep = (matchDate) => { //判断比赛阶段
		let status = 0;
		if (!isMillisecondTimestamp(matchDate)) { //判断毫秒级时间戳
			matchDate = matchDate * 1000
		}
		let newDate = new Date().getTime();
		if (newDate > matchDate) { //赛事进行中
			status = 1;
		}
		return status
	}
	const getMatchJoiner = async (id, loading) => { //获取比赛人员
		const res = await $Api.match.getMatchJoiner({
			page: joinerInfo.page,
			id
		}, loading);
		if (res.code == 1) {
			if (res.data.list.length > 0) {
				let arr = [];
				arr = res.data.list.map(val => {
					if (val.mobile) {
						val.newMobile = maskPhoneNumber(val.mobile);
					}
					return val
				});
				joinerInfo.list = [...joinerInfo.list, ...arr];
				console.log('joinerInfo.list ', joinerInfo.list);
			}
			if (res.data.totalPage > joinerInfo.page) {
				joinerInfo.status = 'loadmore';
				joinerInfo.page++;
			} else {
				joinerInfo.status = 'nomore';
			}
		} else {
			uni.$u.toast(res.msg);
		}
	}
	const getMoreJoiner = () => {
		if (joinerInfo.status === 'nomore' || joinerInfo.status === 'loading') return;
		joinerInfo.status = 'loading';
		setTimeout(() => {
			getMatchJoiner();
		}, 300)
	}
	const refreshData = () => { //刷新详情数据
		getMatchDetail(matchId.value);
	}


	const checkedSign = (item) => {
		if (item.type == 0) { //打开弹窗
			signShow.value = true;
		} else if (item.type == 1) { //关闭报名，刷新数据
			signShow.value = false;
			sginRestJoin();
		} else {
			signShow.value = false;
		}
	};
	const sginRestJoin = () => { //报名成功，重置数据
		joinerInfo.list = [];
		joinerInfo.status = 'loadmore';
		joinerInfo.page = 1;
		matchInfo.value.ordered = 1;
		console.log('matchInfo.join_count', matchInfo.value.join_count, typeof matchInfo.value.join_count ===
			'number');
		if (typeof matchInfo.value.join_count === 'number') {
			matchInfo.value.join_count++;
		}
		getMatchJoiner(matchId.value, true);
	};
	const getSignCode = async () => { //获取签到二维码
		const res = await $Api.match.getSignCode({
			match_id: matchId.value
		}, true)
		if (res.code === 1) {
			signCode.value = res.data.verify_code;
			signCodePop.value = true;
		} else {
			uni.$u.toast(res.msg);
		}
	};
	const saveCode = () => { //保存二维码
		if (upCode.value) {
			upCode.value._saveCode();
		} else {
			uni.$u.toast('保存失败！')
		}
	}
	const closesignCode = () => { //关闭二维码弹窗
		signCodePop.value = false;
		signCode.value = '';
	}
	const changeTab = (e) => {
		tabIndex.value = e.index;
	}
	const changeSwiper = (e) => {
		tabIndex.value = e.detail.current;
	}
	const previewImage = (url, index) => {
		previewImg(url, index);
	}
	const getlocationBysign = async (type = '') => { //获取位置用于签到
		uni.showLoading({
			title: '加载中'
		})
		try {
			const res = await getLocationInf('immediate');
			if (res.latitude && res.longitude) {
				positionInfo.covers.push({
					id: 0,
					latitude: res.latitude,
					longitude: res.longitude,
					width: 36,
					height: 36,
					iconPath: '../../static/nearby/new_positioning.png'
				})
				positionInfo.latitude = res.latitude;
				positionInfo.longitude = res.longitude;
				positionInfo.status = 1;
				if (positionInfo.scale == 16) {
					positionInfo.scale = 15.99;
				} else {
					positionInfo.scale = 16;
				}
				if (type !== 'noopen') {
					signMapShow.value = true;
				}
			} else {
				positionInfo.status = -1;
				if (type !== 'noopen') {
					signMapShow.value = true;
				}
			}
			uni.hideLoading()
		} catch (e) {
			positionInfo.status = -1;
			uni.$u.toast('当前定位失败，无法签到');
			if (type !== 'noopen') {
				signMapShow.value = true;
			}
			uni.hideLoading()
		}

	};
	const closeSign = () => { //关闭赛事报名弹窗
		signShow.value = false;
	}
	const closesignRound = () => { //关闭签到赛事弹窗
		positionInfo.status = -1;
		signMapShow.value = false;
		// positionInfo.show=false;
	}
	const signRound = async () => { //签到接口
		const res = await $Api.match.signRound({
			match_id: matchInfo.value.m_id,
			lat: positionInfo.latitude,
			lng: positionInfo.longitude
		}, true)
		if (res.code === 1) {
			uni.showToast({
				title: '签到成功！'
			});
			matchStore.matchInfo.signRound = 1;
			setTimeout(() => {
				closeSignRound();
			}, 600)
		} else {
			uni.$u.toast(res.msg);
		}
	}
</script>

<style lang="scss" scoped>
	.activityDetails-box {
		flex-direction: column;
		// height: 100vh;
		box-sizing: border-box;
	}

	.activityDetails-info {
		position: relative;

		.content-code {
			width: 120rpx;
			height: 120rpx;
			box-sizing: border-box;
			background-color: #fff;
			-webkit-clip-path: polygon(100% 0, 0 100%, 100% 100%);
			clip-path: polygon(100% 0, 0 100%, 100% 100%);
			z-index: 999;
			position: absolute;
			bottom: 0;
			right: 0;
			// overflow: hidden;

			.code {
				width: 100%;
				height: 100%;
				transform: rotate(90deg);
			}

			.text-box {
				z-index: 999;
				width: 170rpx;
				height: 32rpx;
				background: $btn-bg-color;
				transform: rotate(-45deg);
				text-align: center;
				position: absolute;
				left: -14rpx;
				top: calc(50% - 8rpx);

				.text {
					font-size: 20rpx;
					color: $btn-text-color;

				}
			}
		}
	}

	.swiper {
		width: 100%;
		height: 478rpx;

		.swiper-img-item {
			width: 100%;
			height: 100%;

			.img-item {
				width: 100%;
				height: 100%;
			}
		}
	}

	.tab-box {
		background-color: #111416;
		padding: 0 54rpx;
	}

	.main {
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		// flex: 1;
		height: 100vh;
	}

	.main-content {
		flex: 1;
		padding: 32rpx 20rpx;
	}

	.personnel-box {
		padding: 0 40rpx;
	}

	.swiper-content {
		width: 100%;
		height: 100%;
		box-sizing: border-box;

		.swiper-content-item {
			width: 100%;
			box-sizing: border-box;
			height: 100%;
		}
	}

	.personnel-item {
		justify-content: space-between;
		margin-bottom: 48rpx;

		.ava {
			border-radius: 50%;
			width: 68rpx;
			height: 68rpx;
			overflow: hidden;
		}

		.name {
			font-weight: 500;
			font-size: 34rpx;
			color: $name-color;
			margin: 0 8rpx 0 18rpx;
			width: 180rpx;
			text-overflow: ellipsis;
			white-space: nowrap;
			lines: 1;
			overflow: hidden;
		}

		.lv-icon {
			width: 44rpx;
			height: 38rpx;
		}

		.lv-text {
			color: $lv-color;
			font-size: 20rpx;
			font-weight: bold;
			margin-left: 2rpx;
		}

		.point {
			font-weight: 500;
			font-size: 30rpx;
			// color: $attention-color;
			color: rgba(255, 255, 255, 0.87);
			line-height: 35rpx;
			text-align: right;
			margin-right: 88rpx;
		}

		.follow-bnt {
			border: 2rpx solid $attention-color;
			height: 48rpx;
			width: 96rpx;
			border-radius: 12rpx;

			.text {
				font-weight: bold;
				font-size: 28rpx;
				color: $attention-color;
			}
		}

		.follow-bnt-y {
			.text {
				font-weight: bold;
				font-size: 28rpx;
				color: $unAttention-color;
			}
		}
	}

	// 签到码弹出层
	.signCode-box {
		// width: 480rpx;
		padding: 24rpx;
		box-sizing: border-box;
		flex-direction: column;

		.title {
			font-size: 30rpx;
			color: $name-color;
			font-weight: bold;
			margin-bottom: 24rpx;
		}

		.code-box {
			padding: 16rpx;
			border-radius: 16rpx;
			background-color: #fff;
		}

		.option-box {
			margin-top: 36rpx;
			width: 100%;
			justify-content: space-evenly;

			.option-btn {
				width: 100%;
				height: 48rpx;
				box-shadow: 0rpx 8rpx 16rpx 0rpx rgba(108, 199, 190, 0.38);
				border-radius: 24rpx;
				background: $btn-bg-color;

				.text {
					font-weight: 600;
					font-size: 26rpx;
					color: $btn-text-color;

				}
			}
		}
	}

	// 签到
	.signShow-box {
		width: 640rpx;
		height: 70vh;
		box-sizing: border-box;
		border-radius: 18rpx;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: center;

		.title {
			width: 100%;
			display: block;
			text-align: center;
			font-weight: bold;
			color: $title-color;
			font-size: 30rpx;
		}

		.map-content {
			flex: 1;
			flex-direction: column;
			border-radius: 18rpx;
			background-color: #191c1F;
		}

		.content-box {
			width: 100%;
			height: 40vh;
			border-radius: 18rpx;
			overflow: hidden;

			.map-box {
				height: 100%;
				width: 100%;
			}
		}

		.sign-content {
			padding: 24rpx 20rpx;
			flex-direction: column;
			flex: 1;
			justify-content: space-around;

			.detail {
				width: 100%;
				display: block;
				text-align: left;
				color: $description-color;
				font-size: 28rpx;
			}
		}

		.sign-bnt {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			background: $btn-bg-color;
			box-shadow: 0rpx 8rpx 30rpx 0rpx rgba(108, 199, 190, 0.38);
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			align-self: center;
			// position: absolute;
			// bottom: 42rpx;
			// left: 50%;
			// transform: translateX(-50%);

			.text {
				font-size: 30rpx;
				font-weight: bold;
				color: $btn-text-color;

			}
		}

		.sign-btn-err {
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			flex-direction: column;
			background-color: #666;

			.text {
				font-size: 30rpx;
				font-weight: bold;
				color: #fff;
			}
		}

		.close-btn {
			width: 88rpx;
			height: 88rpx;
			border-radius: 50%;
			background-color: $page-bg-color;
			box-shadow: 0rpx 8rpx 30rpx 0rpx rgba(108, 199, 190, 0.38);
			margin-top: 32rpx;
			// position: absolute;
			// bottom: -112rpx;
			// left: 50%;
			// transform: translateX(-50%);
		}
	}
</style>